package com.st.Service.impl;

import com.api.tickets.ITicketsClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jwt.util.JsonUtils;
import com.order.IdWorker;
import com.st.Mapper.OrderMapper;
import com.st.Service.IOrderService;
import com.st.entity.Order;
import com.st.entity.OrderItem;
import com.st.entity.Result;
import com.st.entity.Ticket;
import com.st.interceptor.UserInfoInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ITicketsClient iTicketsClient;

    @Autowired
    private IdWorker idWorker;
    //添加订单
    @Override
    public Result addOrder(OrderItem order) {

        String userInfo = UserInfoInterceptor.getUserInfo();
        order.setUserId(Integer.parseInt(userInfo));

        Ticket ticket = iTicketsClient.findById(order.getAttractionsId());

        Integer adultNum = order.getAdultNum();
        Integer kidNum = order.getKidNum();
        order.setOrderMoney(adultNum*ticket.getPrice()+(kidNum*ticket.getPrice()/2));
        order.setOrderStatu(1);
        order.setOrderTime(new Date());
        long l = idWorker.nextId();
        order.setId(l+"");
        Map map = new HashMap();
        map.put("id",ticket.getId());
        map.put("num",order.getTicketNum());
        String s = JsonUtils.toString(map);
        Result result = iTicketsClient.delNum(s);
        int i = orderMapper.insert(order);
        return new Result(i==1?true:false,i==1?"添加成功":"添加失败",order.getId());
    }
    //查询
    @Override
    public List<Order> findOrderById(Integer id) {



        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",id);
        return orderMapper.selectList(queryWrapper);
    }
    //删除
    @Override
    public Result delOrder(String userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",userId);
        int i = orderMapper.delete(queryWrapper);
        return new Result(i==1?true:false,i==1?"删除成功":"删除失败");
    }

    //修改
    public Result status(String id){
        Order order = new OrderItem();
        order.setId(id);
        order.setOrderStatu(2);
        int i = orderMapper.updateById(order);
        return new Result(i==1?true:false,i==1?"修改成功":"修改失败");
    }
}
